<template>
  <div class="project-detail-container">
    <div class="project-header">
      <el-button @click="$router.go(-1)" icon="el-icon-arrow-left">返回</el-button>
      <h1>{{ project.name }}</h1>
      <el-tag :type="getStatusType(project.status)">{{ getStatusText(project.status) }}</el-tag>
    </div>

    <el-row :gutter="20">
      <!-- 项目基本信息 -->
      <el-col :span="16">
        <el-card class="project-info">
          <template #header>
            <span>项目信息</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="editProject">编辑</el-button>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="项目编码">{{ project.code }}</el-descriptions-item>
            <el-descriptions-item label="项目经理">{{ project.manager?.full_name || '未分配' }}</el-descriptions-item>
            <el-descriptions-item label="开始日期">{{ formatDate(project.start_date) }}</el-descriptions-item>
            <el-descriptions-item label="计划结束日期">{{ formatDate(project.planned_end_date) }}</el-descriptions-item>
            <el-descriptions-item label="实际结束日期">{{ formatDate(project.actual_end_date) || '未结束' }}</el-descriptions-item>
            <el-descriptions-item label="预算">{{ formatCurrency(project.budget) }}</el-descriptions-item>
            <el-descriptions-item label="实际成本">{{ formatCurrency(project.actual_cost) || '未统计' }}</el-descriptions-item>
            <el-descriptions-item label="优先级">{{ project.priority }}</el-descriptions-item>
            <el-descriptions-item label="进度" :span="2">
              <el-progress :percentage="project.progress" :status="getProgressStatus(project.progress)" />
            </el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">{{ project.description || '暂无描述' }}</el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 项目阶段 -->
        <el-card class="project-phases">
          <template #header>
            <span>项目阶段</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="showCreatePhaseDialog">添加阶段</el-button>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="phase in phases"
              :key="phase.id"
              :timestamp="formatDate(phase.start_date) + ' - ' + formatDate(phase.end_date)"
              :type="getPhaseStatusType(phase.status)">
              <div class="timeline-item-header">
                <h4>{{ phase.name }}</h4>
                <div class="timeline-item-actions">
                  <el-button size="small" @click="editPhase(phase)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deletePhase(phase)">删除</el-button>
                </div>
              </div>
              <p>{{ phase.description }}</p>
              <el-tag size="small" :type="getPhaseStatusType(phase.status)">
                {{ getPhaseStatusText(phase.status) }}
              </el-tag>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 项目任务 -->
        <el-card class="project-tasks">
          <template #header>
            <span>项目任务</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="showCreateTaskDialog">添加任务</el-button>
          </template>
          
          <el-table :data="tasks" style="width: 100%">
            <el-table-column prop="name" label="任务名称" />
            <el-table-column prop="assignee?.full_name" label="负责人" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag size="small" :type="getTaskStatusType(scope.row.status)">
                  {{ getTaskStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="scope">
                <el-tag size="small" :type="getPriorityType(scope.row.priority)">
                  {{ getPriorityText(scope.row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="progress" label="进度" width="150">
              <template #default="scope">
                <el-progress :percentage="scope.row.progress" :status="getProgressStatus(scope.row.progress)" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editTask(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteTask(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 项目侧边栏 -->
      <el-col :span="8">
        <!-- 项目里程碑 -->
        <el-card class="project-milestones">
          <template #header>
            <span>里程碑</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="showCreateMilestoneDialog">添加</el-button>
          </template>
          
          <el-timeline>
            <el-timeline-item
              v-for="milestone in milestones"
              :key="milestone.id"
              :timestamp="formatDate(milestone.due_date)"
              :type="milestone.completed ? 'success' : 'primary'">
              <div class="timeline-item-header">
                <h4>{{ milestone.name }}</h4>
                <div class="timeline-item-actions">
                  <el-button size="small" @click="editMilestone(milestone)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteMilestone(milestone)">删除</el-button>
                </div>
              </div>
              <p>{{ milestone.description }}</p>
              <el-tag size="small" :type="milestone.completed ? 'success' : 'warning'">
                {{ milestone.completed ? '已完成' : '进行中' }}
              </el-tag>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 项目统计 -->
        <el-card class="project-stats">
          <template #header>
            <span>项目统计</span>
          </template>
          
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ tasks.length }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ completedTasks.length }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ phases.length }}</div>
                <div class="stat-label">阶段数</div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="stat-item">
                <div class="stat-number">{{ milestones.length }}</div>
                <div class="stat-label">里程碑</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 编辑项目对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑项目" width="50%">
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" style="width: 100%">
            <el-option label="规划中" value="planning" />
            <el-option label="启动中" value="initiating" />
            <el-option label="执行中" value="executing" />
            <el-option label="监控中" value="monitoring" />
            <el-option label="结束中" value="closing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="on_hold" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度" prop="progress">
          <el-slider v-model="editForm.progress" :step="5" show-stops />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateProject">确认</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 阶段管理对话框 -->
    <PhaseDialog
      v-model="phaseDialogVisible"
      :project-id="project.id"
      :phase="editingPhase"
      @success="fetchPhases(project.id)" />
    
    <!-- 任务管理对话框 -->
    <TaskDialog
      v-model="taskDialogVisible"
      :project-id="project.id"
      :task="editingTask"
      :phases="phases"
      :users="users"
      :parent-tasks="tasks"
      @success="fetchTasks(project.id)" />
    
    <!-- 里程碑管理对话框 -->
    <MilestoneDialog
      v-model="milestoneDialogVisible"
      :project-id="project.id"
      :milestone="editingMilestone"
      :phases="phases"
      @success="fetchMilestones(project.id)" />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PhaseDialog from '../components/project/PhaseDialog.vue'
import TaskDialog from '../components/project/TaskDialog.vue'
import MilestoneDialog from '../components/project/MilestoneDialog.vue'

export default {
  name: 'ProjectDetailView',
  components: {
    PhaseDialog,
    TaskDialog,
    MilestoneDialog
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const editFormRef = ref(null)
    
    const loading = ref(false)
    const editDialogVisible = ref(false)
    
    // 对话框状态
    const phaseDialogVisible = ref(false)
    const taskDialogVisible = ref(false)
    const milestoneDialogVisible = ref(false)
    
    // 编辑对象
    const editingPhase = ref(null)
    const editingTask = ref(null)
    const editingMilestone = ref(null)
    
    // 项目数据
    const project = ref({})
    const phases = ref([])
    const tasks = ref([])
    const milestones = ref([])
    const users = ref([])
    
    // 编辑表单
    const editForm = reactive({
      name: '',
      description: '',
      status: '',
      progress: 0
    })
    
    const rules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' }
      ]
    }
    
    // 计算属性
    const completedTasks = computed(() => {
      return tasks.value.filter(task => task.status === 'completed')
    })
    
    // 获取项目详情
    const fetchProjectDetail = async () => {
      loading.value = true
      try {
        const projectId = parseInt(route.params.id)
        const response = await store.dispatch('fetchProjectById', projectId)
        project.value = response
        
        // 获取项目相关数据
        await Promise.all([
          fetchPhases(projectId),
          fetchTasks(projectId),
          fetchMilestones(projectId),
          fetchUsers()
        ])
      } catch (error) {
        ElMessage.error('获取项目详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取项目阶段
    const fetchPhases = async (projectId) => {
      try {
        const response = await store.dispatch('fetchPhases', projectId)
        phases.value = response
      } catch (error) {
        console.error('获取项目阶段失败:', error)
      }
    }
    
    // 获取项目任务
    const fetchTasks = async (projectId) => {
      try {
        const response = await store.dispatch('fetchTasks', { project_id: projectId })
        tasks.value = response
      } catch (error) {
        console.error('获取项目任务失败:', error)
      }
    }
    
    // 获取项目里程碑
    const fetchMilestones = async (projectId) => {
      try {
        const response = await store.dispatch('fetchMilestones', projectId)
        milestones.value = response
      } catch (error) {
        console.error('获取项目里程碑失败:', error)
      }
    }
    
    // 获取用户列表
    const fetchUsers = async () => {
      try {
        const response = await store.dispatch('fetchUsers')
        users.value = response
      } catch (error) {
        console.error('获取用户列表失败:', error)
      }
    }
    
    // 编辑项目
    const editProject = () => {
      Object.assign(editForm, {
        name: project.value.name,
        description: project.value.description,
        status: project.value.status,
        progress: project.value.progress
      })
      editDialogVisible.value = true
    }
    
    // 更新项目
    const updateProject = () => {
      editFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            await store.dispatch('updateProject', { id: project.value.id, data: editForm })
            ElMessage.success('更新项目成功')
            editDialogVisible.value = false
            fetchProjectDetail() // 重新获取项目详情
          } catch (error) {
            ElMessage.error('更新项目失败')
          }
        }
      })
    }
    

    
    // 显示创建阶段对话框
    const showCreatePhaseDialog = () => {
      editingPhase.value = null
      phaseDialogVisible.value = true
    }
    
    // 编辑阶段
    const editPhase = (phase) => {
      editingPhase.value = phase
      phaseDialogVisible.value = true
    }
    
    // 删除阶段
    const deletePhase = (phase) => {
      ElMessageBox.confirm(
        '确定要删除该阶段吗？删除后无法恢复。',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 这里应该调用API删除阶段
          ElMessage.success('删除阶段成功')
          fetchPhases(project.value.id)
        } catch (error) {
          ElMessage.error('删除阶段失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 显示创建任务对话框
    const showCreateTaskDialog = () => {
      editingTask.value = null
      taskDialogVisible.value = true
    }
    
    // 编辑任务
    const editTask = (task) => {
      editingTask.value = task
      taskDialogVisible.value = true
    }
    
    // 删除任务
    const deleteTask = (task) => {
      ElMessageBox.confirm(
        '确定要删除该任务吗？删除后无法恢复。',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 这里应该调用API删除任务
          ElMessage.success('删除任务成功')
          fetchTasks(project.value.id)
        } catch (error) {
          ElMessage.error('删除任务失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 显示创建里程碑对话框
    const showCreateMilestoneDialog = () => {
      editingMilestone.value = null
      milestoneDialogVisible.value = true
    }
    
    // 编辑里程碑
    const editMilestone = (milestone) => {
      editingMilestone.value = milestone
      milestoneDialogVisible.value = true
    }
    
    // 删除里程碑
    const deleteMilestone = (milestone) => {
      ElMessageBox.confirm(
        '确定要删除该里程碑吗？删除后无法恢复。',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          // 这里应该调用API删除里程碑
          ElMessage.success('删除里程碑成功')
          fetchMilestones(project.value.id)
        } catch (error) {
          ElMessage.error('删除里程碑失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }
    
    // 工具函数
    const formatDate = (date) => {
      if (!date) return ''
      return new Date(date).toLocaleDateString('zh-CN')
    }
    
    const formatCurrency = (amount) => {
      if (!amount) return '¥0.00'
      return `¥${amount.toFixed(2)}`
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        'planning': 'info',
        'initiating': 'warning',
        'executing': 'primary',
        'monitoring': 'success',
        'closing': 'warning',
        'completed': 'success',
        'on_hold': 'warning',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'planning': '规划中',
        'initiating': '启动中',
        'executing': '执行中',
        'monitoring': '监控中',
        'closing': '结束中',
        'completed': '已完成',
        'on_hold': '已暂停',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }
    
    const getPhaseStatusType = (status) => {
      const statusMap = {
        'not_started': 'info',
        'in_progress': 'primary',
        'completed': 'success',
        'delayed': 'warning',
        'on_hold': 'warning'
      }
      return statusMap[status] || 'info'
    }
    
    const getPhaseStatusText = (status) => {
      const statusMap = {
        'not_started': '未开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'delayed': '已延期',
        'on_hold': '已暂停'
      }
      return statusMap[status] || status
    }
    
    const getTaskStatusType = (status) => {
      const statusMap = {
        'not_started': 'info',
        'in_progress': 'primary',
        'completed': 'success',
        'delayed': 'warning',
        'blocked': 'danger',
        'cancelled': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const getTaskStatusText = (status) => {
      const statusMap = {
        'not_started': '未开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'delayed': '已延迟',
        'blocked': '已阻塞',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }
    
    const getPriorityType = (priority) => {
      const priorityMap = {
        'low': 'info',
        'medium': 'warning',
        'high': 'danger',
        'urgent': 'danger'
      }
      return priorityMap[priority] || 'info'
    }
    
    const getPriorityText = (priority) => {
      const priorityMap = {
        'low': '低',
        'medium': '中',
        'high': '高',
        'urgent': '紧急'
      }
      return priorityMap[priority] || priority
    }
    
    const getProgressStatus = (progress) => {
      if (progress >= 100) return 'success'
      if (progress >= 80) return 'success'
      if (progress >= 50) return ''
      if (progress >= 20) return 'warning'
      return 'exception'
    }
    
    onMounted(() => {
      fetchProjectDetail()
    })
    
    return {
      loading,
      project,
      phases,
      tasks,
      milestones,
      completedTasks,
      editForm,
      editFormRef,
      rules,
      editDialogVisible,
      phaseDialogVisible,
      taskDialogVisible,
      milestoneDialogVisible,
      editingPhase,
      editingTask,
      editingMilestone,
      users,
      editProject,
      updateProject,
      showCreatePhaseDialog,
      editPhase,
      deletePhase,
      showCreateTaskDialog,
      editTask,
      deleteTask,
      showCreateMilestoneDialog,
      editMilestone,
      deleteMilestone,
      formatDate,
      formatCurrency,
      getStatusType,
      getStatusText,
      getPhaseStatusType,
      getPhaseStatusText,
      getTaskStatusType,
      getTaskStatusText,
      getPriorityType,
      getPriorityText,
      getProgressStatus
    }
  }
}
</script>

<style scoped>
.project-detail-container {
  padding: 20px;
}

.project-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.project-header h1 {
  margin: 0;
  flex: 1;
}

.project-info,
.project-phases,
.project-tasks,
.project-milestones,
.project-stats {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.timeline-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.timeline-item-header h4 {
  margin: 0;
  flex: 1;
}

.timeline-item-actions {
  display: flex;
  gap: 5px;
}
</style>